package com.wuad.platformwuad.module.study.md5;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

/**
 * AES密钥算法
 *
 * @author wuaodi
 * 2025/2/6
 */
public class AESUtil {
    // AES密钥算法
    private static final String KEY_ALGORITHM = "AES";
    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    private static final String KEY="Ej7SdjOBvlv2Pub8";

    //CBC加密偏移量
    private static final String IVCODE="Ej7SdjOBvlv2Pub8";

    /**
     * AES加密
     */
    public static String encrypt(String data) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            IvParameterSpec iv = new IvParameterSpec(IVCODE.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,iv);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * AES解密
     */
    public static String decrypt(String encryptedData) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), KEY_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IVCODE.getBytes());
            Security.addProvider(new BouncyCastleProvider());
            byte[] encryptedBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(encryptedData);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 验证
    public static void main(String[] args) throws Exception {
//        String data = "张三";AES
//        String encryptedData = encrypt(data); // 加密数据
        String encryptedData = "G8+kex9xhG8O07GDSups4Q==";
        String decryptedData = decrypt(encryptedData); // 解密数据
        System.out.println("加密后的数据: " + encryptedData);
        System.out.println("解密后的数据: " + decryptedData);
    }
}